<template>
  <div class="potentialCustomers">
    <view-header :title="'宿舍管理'"></view-header>
    <div class="search_area">
      <el-row>
        <el-form :form="queryForm" label-width="1rem">
          <el-col :span="6" v-show="user.permission == '01'">
            <el-form-item label="宿舍楼名：">
              <el-input type="text" v-model="queryForm.buildingName" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-show="user.permission == '01'">
            <el-form-item label="宿管名：">
              <el-input type="text" v-model="queryForm.type" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否住满：">
              <el-select v-model="queryForm.fullFlag" placeholder="请选择" style="width: 100%;" clearable>
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
        <el-col :span="6">
          <div class="btn_area">
            <el-button class="confirm" @click="btnClick">查询</el-button>
            <el-button class="cancle" @click="reset">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <table-list :fields="fields" :list="list" :pagination="pagination" :total="total" @sizeChange="handleSizeChange" @currentChange="handleCurrentChange" @handle="onHandle"></table-list>
    <el-dialog title="学生入住操作" :visible.sync="visible" @close="close" width="60%">
      <el-descriptions title="宿舍信息" direction="vertical" :column="3" border>
      <el-descriptions-item label="所属宿舍楼" :contentStyle="{'text-align': 'center'}" :labelStyle="{'text-align': 'center'}">{{ dormitoryForm.buildingName }}</el-descriptions-item>
      <el-descriptions-item label="宿舍管理员" :contentStyle="{'text-align': 'center'}" :labelStyle="{'text-align': 'center'}">{{ dormitoryForm.buildingName }}</el-descriptions-item>
      <el-descriptions-item label="宿舍号" :contentStyle="{'text-align': 'center'}" :labelStyle="{'text-align': 'center'}">{{ dormitoryForm.buildingName }}</el-descriptions-item>
      <el-descriptions-item label="宿舍人数" :contentStyle="{'text-align': 'center'}" :labelStyle="{'text-align': 'center'}">{{ dormitoryForm.peopleNumber }}</el-descriptions-item>
      <el-descriptions-item label="已住人数" :contentStyle="{'text-align': 'center'}" :labelStyle="{'text-align': 'center'}">{{ dormitoryForm.peopleCount }}</el-descriptions-item>
      <el-descriptions-item label="	剩余空间" :contentStyle="{'text-align': 'center'}" :labelStyle="{'text-align': 'center'}">{{ dormitoryForm.freeSpace }}</el-descriptions-item>
    </el-descriptions>
    <div style="display: flex;justify-content: center;margin-top: 0.2rem;">
      <el-transfer 
        v-model="studentIdList" 
        :titles="['未入住学生列表', '已入住学生列表']"
        :button-texts="['移除', '入住']" 
        :data="saveStudentList" 
        filterable
        :filter-method="filterMethod"
        filter-placeholder="请输入学生名"
        @change="transferChange">
      </el-transfer>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button class="confirm" @click="confirm">确 定</el-button>
    </span>
    </el-dialog>
    <el-dialog title="填写卫生情况" :visible.sync="visible2" width="60%" @close="close2">
      <el-row>
        <el-form :form="weishengForm" label-width="0.8rem">
          <el-col :span="8">
            <el-form-item label="宿舍号：">
              <el-input readonly type="text" v-model="weishengForm.dormitoryNumber" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="日期：">
              <el-date-picker
                style="width: 100%;"
                v-model="weishengForm.checkDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分数：">
              <el-input type="text" v-model="weishengForm.score" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="扣分项：">
              <div style="border: 1px solid #ccc;margin-top: 0.2rem;">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editor"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
                />
                <Editor
                  style="height: 500px; overflow-y: hidden;"
                  v-model="html"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="onCreated"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button class="cancle" @click="visible2 = false">取 消</el-button>
        <el-button class="confirm" @click="confirmWeiSheng">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import tableList from '@/components/table.vue'
import viewHeader from '@/components/viewHeader.vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {
  name: 'potentialCustomers',
  components: {
    tableList,
    viewHeader,
    Editor, 
    Toolbar,
  },
  data() {
    return {
      editor: null,
      html: '',
      weishengForm: {
        dormitoryNumber: "",
        checkDate: "",
        score: "",
        dormitoryId: "",
        deductionItem: ""
      },
      toolbarConfig: {
        "toolbarKeys": [
          "headerSelect",
          "blockquote",
          "|",
          "bold",
          "underline",
          "italic",
          {
              "key": "group-more-style",
              "title": "更多",
              "iconSvg": "<svg viewBox=\"0 0 1024 1024\"><path d=\"M204.8 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z\"></path><path d=\"M505.6 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z\"></path><path d=\"M806.4 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z\"></path></svg>",
              "menuKeys": [
                  "through",
                  "code",
                  "sup",
                  "sub",
                  "clearStyle"
              ]
          },
          "color",
          "bgColor",
          "|",
          "fontSize",
          "fontFamily",
          "lineHeight",
          "|",
          "bulletedList",
          "numberedList",
          "todo",
          {
            "key": "group-justify",
            "title": "对齐",
            "iconSvg": "<svg viewBox=\"0 0 1024 1024\"><path d=\"M768 793.6v102.4H51.2v-102.4h716.8z m204.8-230.4v102.4H51.2v-102.4h921.6z m-204.8-230.4v102.4H51.2v-102.4h716.8zM972.8 102.4v102.4H51.2V102.4h921.6z\"></path></svg>",
            "menuKeys": [
                "justifyLeft",
                "justifyRight",
                "justifyCenter",
                "justifyJustify"
            ]
          },
          {
            "key": "group-indent",
            "title": "缩进",
            "iconSvg": "<svg viewBox=\"0 0 1024 1024\"><path d=\"M0 64h1024v128H0z m384 192h640v128H384z m0 192h640v128H384z m0 192h640v128H384zM0 832h1024v128H0z m0-128V320l256 192z\"></path></svg>",
            "menuKeys": [
                "indent",
                "delIndent"
            ]
          },
          "emotion",
          "|",
          "insertLink",
          "insertTable",
          "codeBlock",
          "divider",
          "|",
          "undo",
          "redo",
          "|",
        ],
        "excludeKeys": [],
        "insertKeys": {
          "index": 0,
          "keys": []
        },
        "modalAppendToBody": false
      },
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default', // or 'simple',
      queryForm: {
        "buildingName": "",
        "fullFlag": "",
        "userName": "",
        "adminId": ""
      },
      list: [],
      fields: [
        {
          prop: 'rowNum',
          label: '序号',
          align: 'center'
        },
        {
          prop: 'dormitoryNumber',
          label: '宿舍号',
          align: 'center'
        },
        {
          prop: 'peopleNumber',
          label: '宿舍人数',
          align: 'center'
        },
        {
          prop: 'peopleCount',
          label: '已住人数',
          align: 'center'
        },
        {
          prop: 'freeSpace',
          label: '剩余空间',
          align: 'center'
        },
        {
          prop: 'buildingName',
          label: '宿舍楼名',
          align: 'center'
        },
        {
          prop: 'userName',
          label: '宿管管理员',
          align: 'center'
        },
        {
          prop: 'oper',
          label: '操作',
          align: 'center',
          btns: [
            {type: 'primary',desc:'学生入住'},
            {type: 'success',desc:'卫生检查'},
          ]
        }
      ],
      pagination: {
        currentPage: 1,
        pageSize: 10
      },
      total: 0,
      user: {},
      saveStudentList: [],
      dormitoryForm: {},
      visible: false,
      studentIdList: [],
      unStudentList: [],
      dormitoryId: [],
      visible2: false,
    }
  },
  methods: {
    confirmWeiSheng() {
      this.weishengForm.deductionItem = this.editor.getHtml()
      this.weishengForm.dormitoryId = this.dormitoryId;
      console.log(this.weishengForm);
      this.$http(this.$api.evaluation.create,this.reqData(this.weishengForm)).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.visible2 = false;
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    transferChange(val) {
      console.log(val);
      if (val.length > Number(this.dormitoryForm.peopleNumber)) {
        this.$confirm('当前选择入住人数大于宿舍容纳人数，请重新选择', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error',
          center: true,
          showCancelButton: false,
        }).then(() => {
        }).catch(() => {          
        });
      }
    },
    confirm() {
      console.log(this.studentIdList,this.dormitoryId);
      let url = this.$api.dormitory.saveStudent
      let obj = {
        dormitoryId: this.dormitoryId,
        studentIdList: this.studentIdList
      }
      if (this.studentIdList.length > Number(this.dormitoryForm.peopleNumber)) {
        this.$confirm('当前选择入住人数大于宿舍容纳人数，请重新选择', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error',
          center: true,
          showCancelButton: false,
        }).then(() => {
        }).catch(() => {          
        });
      } else {
        this.$http(url,this.reqData(obj)).then(res => {
          if (res.data.code === 200) {
            this.visible = false
            this.$message.success(res.data.message)
            this.queryDormitoryList();
          } else {
            this.$message.error(res.data.message)
          }
        })
      }
    },
    close() {
      this.dormitoryForm = {};
      this.saveStudentList = [];
      this.studentIdList = [];
      this.unStudentList = [];
    },
    close2() {
      this.weishengForm = {
        dormitoryNumber: "",
        checkDate: "",
        score: "",
        dormitoryId: "",
        deductionItem: ""
      };
      this.editor.clear();
    },
    onHandle(data) {
      let {row,type} = data;
      console.log(row);
      this.dormitoryId = row.uuid;
      // 分配学生入住
      if (type == 'primary') {
        this.queryUnStudentList(row.buildingGender);
        setTimeout(() => {
          this.$http(this.$api.dormitory.info,this.reqData(row.uuid)).then(res => {
            if (res.data.code == 200) {
              this.dormitoryForm = res.data.data
              let {tblUsers} = this.dormitoryForm
              this.studentIdList = tblUsers.map(item => item.uuid)
              this.saveStudentList = [...tblUsers,...this.unStudentList]
              this.saveStudentList.forEach(item => {
                item.key = item.uuid;
                item.label = item.userName;
              })
              console.log('全部列表',this.saveStudentList);
              console.log('未入住',this.saveStudentList);
              console.log('已入住',this.studentIdList);
              this.visible = true;
            } else {
              this.$message.error(res.data.message)
            }
          })
        },500)
      } else {
        // 卫生检查
        console.log('卫生');
        this.weishengForm.dormitoryNumber = row.dormitoryNumber
        this.visible2 = true;
      }
    },
    filterMethod(query,item) {
      return item.userName.indexOf(query) > -1;
    },
    // 根据当前宿舍楼是男、女宿舍楼来查询未分配学生列表
    queryUnStudentList(gender) {
      this.$http(this.$api.user.unStudentList,this.reqData(gender)).then(res => {
        if (res.data.code == 200) {
          this.unStudentList = res.data.data;
          console.log(this.unStudentList);
        }
      })
    },
    btnClick() {
      this.queryDormitoryList();
    },
    reset() {
      this.queryForm = {
        "buildingName": "",
        "fullFlag": "",
        "userName": "",
        "adminId": ""
      };
      this.queryForm.adminId = this.user.permission == '01' ? "" : this.user.uuid;
      this.queryDormitoryList();
    },
    queryDormitoryList() {
      console.log(this.queryForm);
      this.$http(this.$api.dormitory.list,this.reqData(this.queryForm,this.pagination.currentPage,this.pagination.pageSize)).then(res => {
        if (res.data.code === 200) {
          let data = res.data.data;
          this.list = data.list;
          this.list.forEach((item,index) => {
            item.rowNum = (this.pagination.currentPage - 1) * this.pagination.pageSize + index + 1
          })
          this.total = this.list.length;
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleSizeChange(val) {
      console.log(val);
      this.pagination.pageSize = val;
      this.queryDormitoryList();
    },
    handleCurrentChange(val) {
      console.log(val);
      this.pagination.currentPage = val;
      this.queryDormitoryList();
    },
    onCreated(editor) {
      console.log(editor);
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    getHtml() {
      const text = this.editor.getHtml()
      console.log(text);
      console.log(toolbar.getConfig());
    },
  },
  mounted() {
    this.user = JSON.parse(sessionStorage.getItem('user'));
    console.log(this.user);
    this.queryForm.adminId = this.user.permission == '01' ? "" : this.user.uuid;
    this.queryDormitoryList();
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped>
.potentialCustomers {
  background: #fff;
  overflow: hidden;
  padding-bottom: 0.15rem;
}
</style>